<template>
  <div class="add-data-collect-task">
    <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
      <back :backOption="backOption" />
      <div class="h-full">
        <el-form
          @submit.prevent
          scroll-to-error
          label-width="180px"
          :model="formData.data"
          ref="formRef"
          :rules="rules"
        >
          <h3 class="m-section-title">
            <span class="m-section-title__text">任务基本信息</span>
          </h3>
          <el-form-item
            label="任务名称"
            prop="name"
            class="col-item"
            v-if="(jumpType != '2' || assetType != 2) && !route.query.isOffLine"
          >
            <ns-input
              :rows="6"
              type="text"
              v-model.trim="formData.data.name"
              placeholder="请输入任务名称"
              clearable
              :maxlength="50"
            />
          </el-form-item>
          <el-form-item
            v-if="(assetType === 4 && !route.query.isOffLine) || route.query.isAudit"
            label="出境批次"
            prop="batchNumVO"
            class="batch-num"
          >
            <el-select-v2
              placeholder="请选择出境批次"
              clearable
              v-model="formData.data.batchNumVO"
              :options="exitBatch"
              :props="batchProps"
              :loading="batchLoading"
              @change="handleBatchChange"
              class="mr-50%"
            />
            <div class="exit-batch-info mb-0px" v-if="formData.data.batchNumVO">
              <span class="pr-16px">
                <span class="text-info">联系人: </span>
                <span>{{ currentBatch?.linkName }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">单位名称: </span>
                <span>{{ currentBatch?.unitName }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">联系方式: </span>
                <span>{{ currentBatch?.linkWay }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">接收者名称: </span>
                <span>{{ currentBatch?.receiverName }}</span>
              </span>
              <p class="my-0">
                <span class="text-info">出境场景描述: </span>
                <span>{{ currentBatch?.sceneDesc }}</span>
              </p>
            </div>
          </el-form-item>
          <el-form-item label="归属机构:" prop="deptId">
            <el-cascader
              ref="deptCascader"
              @change="handleDeptChange"
              v-model="formData.data.deptId"
              placeholder="请选择归属机构"
              :props="formData.cascaderProps"
              :options="formData.deptList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item label="归属系统:" prop="sysId">
            <el-cascader
              ref="systemCascader"
              @change="handleSysChange"
              v-model="formData.data.sysId"
              placeholder="请选择归属系统"
              :props="formData.systemCascaderProps"
              :options="formData.systemList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <Icon icon="svg-icon:tips" />
            <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
          </el-form-item>
          <el-form-item
            label="数据标准:"
            prop="dataStandardId"
            v-if="jumpType == '2' || assetType == 4"
            class="col-item"
          >
            <el-select
              v-model="formData.data.dataStandardId"
              clearable
              placeholder="请选择数据标准"
            >
              <el-option
                v-for="item in markedTemplateList"
                :label="item.dataStandardName"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="采集对象类型"
            prop="collectTargetType"
            v-if="jumpType != '2' && dataType == 'db'"
          >
            <el-radio-group v-model="formData.data.collectTargetType" class="ml-4">
              <el-radio :label="1" :disabled="jumpType == '2'">在线数据源</el-radio>
              <el-radio :label="2">离线数据文件</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="
              (formData.data.collectTargetType === 1 || dataType !== 'db') && !route.query.isOffLine
            "
            required
            label="待查数据源对象"
          >
            <div class="mb-5px">
              <el-button
                type="primary"
                plain
                @click="taskImport(1)"
                v-if="dataType == 'db'"
                :disabled="!formData.data.sysId && !formData.data.deptId"
              >
                导入数据库数据源
              </el-button>
              <el-button
                type="primary"
                plain
                @click="taskImport(2)"
                :disabled="!formData.data.sysId && !formData.data.deptId"
                v-else
              >
                导入文件服务器数据源
              </el-button>
              <el-button type="danger" plain @click="deleteRow">删除</el-button>
            </div>
            <div class="w-full">
              <AsyncTable
                ref="tableRef"
                v-bind="tableOption"
                :fetchData="fetchData"
                @selection-change="handleSelectionChange"
              />
            </div>
          </el-form-item>
          <div v-else>
            <el-form-item class="col-item" label="导入模板">
              <el-button
                type="primary"
                plain
                :icon="Download"
                @click="downloadTemplate('excel', '1', 'xlsx')"
                :loading="exportLoading"
              >
                下载EXCEL模板
              </el-button>
              <el-button
                type="primary"
                plain
                :icon="Download"
                @click="downloadTemplate('json', '2', 'json')"
                :loading="exportLoading"
              >
                下载Json模板
              </el-button>
              <el-button
                type="primary"
                plain
                :icon="Download"
                @click="downloadTemplate('csv', '3', 'csv')"
                :loading="exportLoading"
              >
                下载csv模板
              </el-button>
            </el-form-item>
            <el-form-item class="col-item" label="上传文件" prop="fileList">
              <el-upload
                class="w-50%"
                
                 multiple drag 
                v-model:file-list="fileList"
                :action="actionUrl"
                :headers="uploadHeaders"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
                :on-error="uploadError"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text"> 将文件拖至此处，或<em>点击上传</em> </div>
                <template #tip>
                  <div>
                    <Icon icon="svg-icon:tips" />
                    <span style="color: #cccccc">
                      支持上传根据模板编辑后的数据excel文件、Json文件、csv文件以及数据库导出的sql文件,单个文件需对应一个资产
                    </span>
                  </div>
                  <div>
                    <Icon icon="svg-icon:tips" />
                    <span style="color: #cccccc"> 仅允许上传单个、批量文件或压缩包 </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </div>
          <h3 class="m-section-title" v-if="jumpType != '2' && assetType !== 4">
            <span class="m-section-title__text">扫描参数设置</span>
          </h3>
          <el-form-item
            label="扫描参数模板"
            label-width="180px"
            prop="scanTemplateId"
            class="mt5"
            v-if="jumpType != '2' && assetType !== 4"
          >
            <el-select
              v-model="formData.data.scanTemplateId"
              filterable
              style="width: 240px"
              @change="handleScanMode"
              clearable
            >
              <el-option
                v-for="item in scanModeOptions"
                :key="'scanTemplate' + item.id"
                :label="item.templateName"
                :value="item.id"
              />
            </el-select>
            <div v-if="templateDesc" class="w-full color-#909399">
              <el-icon class="v-middle" color="#909399" size="16"><InfoFilled /></el-icon>
              <span class="pl-5px">{{ templateDesc }}</span>
            </div>
          </el-form-item>
          <el-form-item label-width="65px" class="collect-scan-param">
            <ScanParam
              v-if="jumpType != '2' && assetType !== 4"
              style="width: 100%"
              :params="scanModeDetail"
              readonly
              :type="jumpType == '2' || formData.data.collectTargetType === 2 ? '1' : '0'"
              :dataType="dataType"
            />
          </el-form-item>
          <div style="text-align: center">
            <el-button @click="router.go(-1)">取消</el-button>
            <el-button type="primary" @click="submit" :disabled="disabled">确定</el-button>
          </div>
        </el-form>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { cloneDeep } from 'lodash-es'
import { sysFilterMethod } from '@/utils/selectFilter'
import { getAssetTypeEnum } from '@/api/asset/taskManage/dataCollect'
import ScanParam from '../../scanStrategy/detail.vue'
import { UploadFilled } from '@element-plus/icons-vue'
import back from '@/components/Back/index.vue'
import { Hide, View } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElButton, ElMessage } from 'element-plus'
import { handleTree } from '@/utils/tree'
import download from '@/utils/download'
import * as api from '@/api/asset/taskManage'
import { getSimpleDeptList } from '@/api/system/dept'
import { saveTask, getTaskDetail, editTask, batchNumInfo } from '@/api/asset/taskManage/dataCollect'
import { getScanPolicyTemplatePage, getScanPolicyTemplate } from '@/api/asset/scanStrategy/index'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { responseType } from './addFlieInterface'
import AsyncTable from '@/components/AsyncTable'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'

const route = useRoute()
const router = useRouter()
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const dataType = ref(route.query.dataType)
const editId = ref(route.query.id)
const jumpType = ref(route.query.jumpType)
const tableRef = ref()
const disabled = ref(false)
const taskType = ref(2)
const markedTemplateList = ref([])
const batchLoading = ref(false)
const batchProps = { label: 'batchNum', value: 'jsonStr', key: 'batchNum', tag: '123' }
const currentBatch = ref({})
const backOption = reactive({
  title: `${!route.query.isOffLine ? (dataType.value === 'db' || jumpType.value == '2' ? '数据库采集任务（本系统不处理涉密数据，被扫描数据源请勿存有涉密数据）' : '文件服务器采集任务（本系统不处理涉密数据，被扫描数据源请勿存有涉密数据）') : '待确认数据库数据资产'}`
})
const scanModeOptions = ref([])
const actionUrl: string = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})

const handleBatchChange = (val) => {
  if (val) {
    currentBatch.value = JSON.parse(val)
  } else {
    currentBatch.value = {}
  }
}
const fileList = ref<responseType[]>([])
const scanModeDetail = ref({})
const templateDesc = computed(() => {
  if (formData.data.scanTemplateId) {
    return scanModeOptions.value.filter((item) => item.id === formData.data.scanTemplateId)[0]
      ?.templateDesc
  } else {
    return ''
  }
})
const exitBatch = ref([])
const handleShowIp = (row) => {
  row.isShowIp = !row?.isShowIp
}
const tableOption = reactive({
  columns: [
    {
      type: 'selection',
      width: '40px'
    },
    {
      label: '数据源名称',
      prop: 'name'
    },
    {
      label: '资产IP:端口',
      width: 170,
      render: ({ row }) => {
        return (
          <>
            <div style="display:flex;align-items:center;justify-content:space-between;">
              {row?.isShowIp ? (
                <span>{row.port ? row.ip + ':' + row.port : row.ip}</span>
              ) : (
                <span style="font-size:17px">***********</span>
              )}
              {row?.isShowIp ? (
                <el-icon>
                  <Hide onClick={() => handleShowIp(row)} />
                </el-icon>
              ) : (
                <el-icon>
                  <View onClick={() => handleShowIp(row)} />
                </el-icon>
              )}
            </div>
          </>
        )
      }
    },
    {
      label: '资产类型',
      prop: 'assetTypeName',
      width: 150,
      align: 'center',
      render: (cellData) => cellData || '--'
    },
    {
      label: '库名',
      prop: 'dbName'
    },
    {
      label: '归属机构',
      prop: 'department'
    },
    {
      label: '归属系统',
      prop: 'system'
    },
    {
      label: '连接信息',
      prop: 'configStatus',
      minWidth: 150,
      align: 'center',
      render: (cellData) => (
        <span class={cellData === 1 ? 'text-success' : 'text-info'}>
          {cellData === 1 ? '已配置' : '未配置'}
        </span>
      )
    },
    {
      label: '操作项',
      minWidth: 150,
      render: ({ row, $index }) => (
        <ElButton
          type="primary"
          text
          size="small"
          onClick={(_) => addDatabaseInfo('edit', row, $index)}
        >
          配置连接信息
        </ElButton>
      )
    }
  ],
  selectionRows: [],
  currentDataIdx: -1,
  page: 1,
  pageSize: 10,
  ids: [],
  allData: [],
  data: [],
  count: 0
})

const assetType = computed(() => {
  return route.name === 'AddDataCollectTask' || route.name === 'addOfflineData' ? 2 : 4
})

const formData = reactive({
  data: {
    name: '',
    collectTargetType: 1,
    collectionAssetSaveReqVOList: [],
    fileList: [],
    dataStandardId: '',
    batchNumVO: '',
    sysId: '',
    deptId: ''
  },
  systemList: [],
  deptList: [],
  cascaderProps: {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
  },
  systemCascaderProps: {
    checkStrictly: true,
    label: 'value',
    value: 'id',
    children: 'children',
    emitPath: false
  }
})
const isRequired = computed(() => {
  return !formData.data.deptId && !formData.data.sysId
})
const fileListValidator = (rule: any, value: any, callback: any) => {
  if (fileList.value.length === 0) {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const rules = computed(() => ({
  name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  collectTargetType: [{ required: true, message: '采集对象类型不能为空', trigger: 'change' }],
  collectionAssetSaveReqVOList: [
    { required: true, message: '待查数据源对象不能为空', trigger: 'change' }
  ],
  fileList: [{ required: true, validator: fileListValidator, trigger: 'change' }],
  scanTemplateId: [{ required: true, message: '扫描参数模板不能为空', trigger: 'change' }],
  dataStandardId: [{ required: true, message: '数据标准不能为空', trigger: 'change' }],
  batchNumVO: [{ required: true, message: '批次号不能为空', trigger: 'change' }]
}))
onMounted(async () => {
  //区分资产类型
  const assetIsDB = dataType.value === 'db'
  const isJumpType2 = jumpType.value == '2'

  if (assetType.value === 2) {
    taskType.value = assetIsDB || isJumpType2 ? 2 : 3
  } else if (assetType.value === 4) {
    taskType.value = assetIsDB ? 4 : 5
  }
  //根据资产类型及来源设置采集对象类型
  if (jumpType.value == '2') {
    formData.data.collectTargetType = 2
    if (jumpType.value == '2') {
      formData.data.name = new Date().getTime().toString()
    }
  }
  if (route.query.tableData) {
    onImportTaskSubmit(
      Array.isArray(JSON.parse(route.query.tableData))
        ? JSON.parse(route.query.tableData)
        : [JSON.parse(route.query.tableData)],
      true
    )
  }
  const { data } = await dataStandardsPage({ page: 1, pageSize: 100000, type: 1, status: '1' })
  markedTemplateList.value = data
  if (jumpType.value == '2' || assetType.value == 4) {
    formData.data.dataStandardId = markedTemplateList.value[0]?.id
  }
  getDeptList()
  getSystemList()
  initData()
  if (editId.value) {
    const data = await getTaskDetail({ id: editId.value })
    Object.keys(data).forEach((item) => {
      data[item] = data[item] ?? formData.data[item]
    })
    formData.data = data

    handleScanMode(formData.data.scanTemplateId)
    if (data.collectTargetType === 1) {
      tableOption.allData = cloneDeep(data.collectionAssetSaveReqVOList)
      tableRef?.value?.fetchData()
    } else {
      fileList.value = data.fileList || []
    }
  }
  if ((assetType.value === 4 && !route.query.isOffLine) || route.query.isAudit) {
    if (editId.value && formData.data.batchNum) {
      currentBatch.value = {
        batchNum: formData.data.batchNum,
        linkName: formData.data.linkName,
        linkWay: formData.data.linkWay,
        sceneDesc: formData.data.sceneDesc,
        unitName: formData.data.unitName,
        receiverName: formData.data.receiverName
      }
      formData.data.batchNumVO = formData.data.batchNum
    }
    batchNumInfo({})
      .then(({ data }) => {
        exitBatch.value = data.map((item) => {
          item.jsonStr = JSON.stringify(item)
          return item
        })
        if (editId.value && formData.data.batchNum) {
          exitBatch.value.push({
            ...currentBatch.value,
            disabled: true,
            jsonStr: JSON.stringify(currentBatch.value)
          })
        }
        batchLoading.value = false
      })
      .catch(() => {
        batchLoading.value = false
      })
  }
  getAssetType()
})

async function getDeptList() {
  const data = await getSimpleDeptList()
  formData.deptList = data
  if (!editId.value && route.query.inner !== 'source') {
    formData.data.deptId = data[0]?.id || ''
  }
}

async function getSystemList() {
  const data = await api.getSimpleSystemList()
  formData.systemList = handleTree(data, 'id', 'pid')
  if (!editId.value && route.query.inner !== 'source') {
    formData.data.sysId = formData?.systemList[0]?.id || ''
  }
}

const handleSysChange = () => {
  tableOption.allData = []
  if (tableRef.value) {
    tableRef.value.fetchData()
  }
}
const handleDeptChange = () => {
  tableOption.allData = []
  if (tableRef.value) {
    tableRef.value.fetchData()
  }
}

//限制上传类型
const beforeUpload = (file: any) => {
  const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
  const isExcel =
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel' ||
    file.name.endsWith('.xls') ||
    file.name.endsWith('.xlsx')
  const isJSON = file.type === 'application/json' || file.name.endsWith('.json')
  const isZip = file.type === 'application/zip' || file.name.endsWith('.zip')
  const isRar = file.type === 'application/x-rar-compressed' || file.name.endsWith('.rar')
  const is7z = file.type === 'application/x-7z-compressed' || file.name.endsWith('.7z')
  const isSQL = file.type === 'application/sql' || file.name.endsWith('.sql')
  if (!isCSV && !isExcel && !isJSON && !isZip && !isRar && !is7z && !isSQL) {
    ElMessage.error('上传文件只能是 csv, excel, json,sql或 .zip,.rar,.7z 格式压缩包!')
    return false
  }
  return true
}
// 上传成功提示
const uploadSuccess = (res: any): void => {
  res.code == 200
    ? proxy.$message.success('上传成功')
    : proxy.$message.error(res.message || '上传失败')
  fileList.value = fileList.value.filter((item) => {
    return item.response.code == 200
  })
  proxy.$refs.formRef.validate()
}
//上传失败提示
const uploadError = (res: any): void => {
  proxy.$message.error(res.message)
}

const handleScanMode = async (value: number) => {
  let data = await getScanPolicyTemplate(value)
  scanModeDetail.value = data
}

//获取扫描策略列表
const initData = async () => {
  const { data } = await getScanPolicyTemplatePage({
    pageSize: 99999,
    page: 1,
    status: '1',
    templateType: dataType.value === 'db' ? '0' : '1'
  })
  scanModeOptions.value = data
}

async function fetchData({ page, pageSize }) {
  tableOption.page = page
  tableOption.pageSize = pageSize
  const data = tableOption.allData.slice((page - 1) * pageSize, page * pageSize)

  return {
    data: data,
    count: tableOption.allData.length
  }
}

const submit = () => {
  if (formData.data.collectTargetType == 2) {
    formData.data.fileList = fileList.value.map((item) => {
      if (item.name && item.path) {
        // 处理编辑带过来的数据
        return {
          path: item.path,
          name: item.name
        }
      } else {
        return {
          path: item.response.data?.path,
          name: item.response.data?.name
        }
      }
    })
  }
  proxy.$refs.formRef.validate(async (valid: Boolean) => {
    if (valid) {
      // 判断数据库是否配置
      if (formData.data.collectTargetType == 1) {
        // 所有数据库是否配置
        if (tableOption.allData.some((item) => item.configStatus === 0)) {
          ElMessage.error('请配置数据源！')
          return
        }
        formData.data.collectionAssetSaveReqVOList = cloneDeep(tableOption.allData)
        if (!editId.value) {
          formData.data.collectionAssetSaveReqVOList.forEach((item, index) => {
            item.datasourceId = item.id
            item.id = null
          })
        }
      }
      disabled.value = true
      if (formData.data.collectTargetType == 2) {
        formData.data.collectionAssetSaveReqVOList = []
      }
      if (editId.value) {
        formData.data.collectionAssetSaveReqVOList.forEach((item, index) => {
          if (!item.datasourceId && item.id) {
            ;[item.datasourceId, item.id] = [item.id, null]
            // item.datasourceId = item.id
            // item.id = null
          }
        })
        if (editId.value && formData.data?.batchNum == formData.data?.batchNumVO) {
          formData.data.batchNumVO = JSON.stringify(currentBatch.value)
        } else if (!formData.data.batchNumVO) {
          formData.data.batchNumVO = JSON.stringify({
            batchNum: '',
            linkName: '',
            linkWay: '',
            sceneDesc: '',
            unitName: '',
            receiverName: ''
          })
        }
        const { code } = await editTask(
          Object.assign({}, formData.data, {
            id: editId.value,
            type: route.query.isOffLine ? 7 : assetType.value,
            taskType: route.query.isOffLine ? 7 : taskType.value,
            jumpType: jumpType.value,
            deptId: formData.data.deptId == '' ? '0' : formData.data.deptId
          })
        ).catch(() => {
          disabled.value = false
        })
        code == 200 ? message.success('修改成功') : message.error('修改失败')
        code == 200 && router.go(-1)
      } else {
        const { code } = await saveTask({
          ...formData.data,
          type: route.query.isOffLine ? 7 : assetType.value,
          jumpType:
            jumpType.value == '2' || (assetType.value == 4 && dataType.value == 'db') ? '2' : '1',
          taskType: route.query.isOffLine ? 7 : taskType.value,
          deptId: formData.data.deptId == '' ? '0' : formData.data.deptId
        }).catch(() => {
          disabled.value = false
        })
        code == 200 ? message.success('新增成功') : message.error('新增失败')
        code == 200 && router.go(-1)
      }
      disabled.value = false
    } else {
      proxy.$modal.msgError('必填项不能为空，请检查')
    }
  })
}
const exportLoading = ref(false)
const downloadTemplate = async (type, downloadType, suffix) => {
  try {
    // 发起导出
    exportLoading.value = true
    const data = await api.downLoadExcel({ type: downloadType })
    download[type](data, `资产导入${type}模板文件.${suffix}`)
  } catch {
  } finally {
    exportLoading.value = false
  }
}

//数据写入表格
function onImportTaskSubmit(data, hideTip) {
  if (data?.length > 0) {
    // 数据去重
    if (!formData.data.sysId) {
      formData.data.sysId = data[0].sysId
    }
    if (formData.data.deptId == '0' || !formData.data.deptId) {
      formData.data.deptId = data[0].deptId
    }

    const idSet = new Set(tableOption.allData.map((item) => item.id)) // O(n) 创建 Set
    for (let item of data) {
      if (!idSet.has(item.id)) {
        tableOption.allData.unshift(item) // 直接将新元素插入到开头，避免创建新数组
      }
    }

    // const newArray = []
    // const ids = tableOption.allData.map((item) => item.id)
    // for (const k in data) {
    //   if (!ids.includes(data[k].id)) {
    //     newArray.push(data[k])
    //   }
    // }
    // tableOption.allData = newArray.concat(tableOption.allData)
    query()
  }
  !hideTip && proxy.$modal.msgSuccess('导入成功')
}
const taskImport = (datasourceType) => {
  proxy.$Drawer({
    title: '添加数据源对象',
    component: import('@/views/asset/assetDiscovery/taskManage/add/ImportTask.vue'),
    size: '75%',
    params: {
      datasourceType,
      sysId: formData.data.sysId,
      deptId: formData.data.deptId,
      callBack: (data) => {
        onImportTaskSubmit(data)
      }
    }
  })
}
const addDatabaseInfo = (mode, data, index) => {
  tableOption.currentDataIdx = index
  proxy.$Drawer({
    title: mode === 'add' ? '添加资产对象' : '编辑资产对象',
    component: import('@/views/asset/components/Database.vue'),
    size: '50%',
    params: {
      isAdd: mode === 'add',
      info: mode == 'edit' ? data : -1,
      source: fileType.includes(data.assetTypeName) ? 'fileSource' : 'dbSource',
      isConfig: true,
      callBack: (data) => {
        if (mode === 'add') {
          tableOption.allData.unshift(data)
          query()
        } else {
          tableOption.allData[
            (tableOption.page - 1) * tableOption.pageSize + tableOption.currentDataIdx
          ] = data
          tableRef.value.fetchData()
        }
      }
    }
  })
}
const fileType = []
//获取文件类型资产列表
async function getAssetType() {
  const data = await getAssetTypeEnum()
  let type = []
  for (let i in data) {
    if (data[i].name == '文件服务') {
      type = data[i]
    }
  }
  for (let item in type.children[0]?.children) {
    fileType.push(type.children[0]?.children[item].showName)
  }
}
// 多选框选中数据
function handleSelectionChange(selection) {
  // 清掉上次的勾选状态
  tableOption.selectionRows.map((row) => {
    row.checked = false
    return row
  })
  tableOption.selectionRows = selection
  // 重新设置勾选状态
  selection.map((row) => {
    row.checked = true
    return row
  })
}
function deleteRow() {
  ElMessageBox.confirm('你确定要删除所选数据吗？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableOption.allData = tableOption.allData.filter((item) => !item.checked)
    query()
  })
}

function query() {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
</script>

<style lang="scss">
.add-data-collect-task {
  .ns-input {
    width: 50%;
  }

  .el-cascader {
    width: 50%;

    .ns-input {
      width: 100%;
    }
  }

  .collect-scan-param,
  .batch-num,
  .col-item {
    .el-select {
      width: 50%;
    }
  }

  .exit-batch-info {
    color: #606266;

    .text-info {
      color: #606266;
    }
  }

  .m-section-title {
    margin-bottom: 20px;
    height: 24px;
    line-height: 24px;
    font-size: 16px;

    &::before {
      content: ' ';
      display: inline-block;
      width: 4px !important;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 10px;
      position: relative;
      top: 3px;
    }

    .m-section-title__text {
      font-weight: 500;
      font-family: PingFangSC-Medium;
    }
  }

  .text-info {
    color: #ff0d00;
  }

  .text-success {
    color: #67c23a;
  }
}
</style>
